package com.able.concurrency.t2;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author abel.he
 * @data 2018/8/18 12:39
 * @describe 可中断阻塞锁状态 线程不打断 会一直等待获取锁标记
 */
public class Test3 {

    Lock lock = new ReentrantLock();

    void m1() {
        try {
            lock.lock();
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + " m1():" + i);
                TimeUnit.SECONDS.sleep(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    void m2() {
        try {
            // 阻塞等待 可以被线程打断 打断后会进入catch方法
            lock.lockInterruptibly();
            System.out.println(Thread.currentThread().getName() + " m2():");
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + " m2(): InterruptedException");
//            e.printStackTrace();
        } finally {
            try {
                lock.unlock();
            } catch (Exception e) {
//                e.printStackTrace();
                System.out.println("m2() lock.unlock() 异常");
            }
        }
    }

    public static void main(String[] args) {
        final Test3 test3 = new Test3();
        new Thread(new Runnable() {
            public void run() {
                test3.m1();
            }
        }).start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                test3.m2();
            }
        });
        thread2.start();
        thread2.interrupt();
    }

}
